import React, { useState } from 'react';
import { Modal, Form, Select, Input, Radio, Table, message, Space, Button } from 'antd';
import { batchOperateUsers } from '@/services/userManagementApi';

interface BatchOperationModalProps {
  visible: boolean;
  selectedUsers: USER.UserModel[];
  onCancel: () => void;
  onSuccess: () => void;
}

const BatchOperationModal: React.FC<BatchOperationModalProps> = ({
  visible,
  selectedUsers,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [operationType, setOperationType] = useState<string>('');

  // 操作类型选项
  const operationOptions = [
    { label: '批量删除', value: 'delete' },
    { label: '修改状态', value: 'update_status' },
    { label: '修改角色', value: 'update_role' },
    { label: '重置密码', value: 'reset_password' },
    { label: '发送通知', value: 'send_notification' },
  ];

  // 状态选项
  const statusOptions = [
    { label: '正常', value: 'active' },
    { label: '未激活', value: 'inactive' },
    { label: '已封禁', value: 'banned' },
  ];

  // 角色选项
  const roleOptions = [
    { label: '用户', value: 'user' },
    { label: '管理员', value: 'admin' },
  ];

  // 处理操作类型变化
  const handleOperationTypeChange = (value: string) => {
    setOperationType(value);
    form.resetFields(['status', 'role', 'password', 'notification_title', 'notification_content']);
  };

  // 处理提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const userIds = selectedUsers.map(user => user.id);
      
      let operationData: any = {
        operation: values.operation,
        user_ids: userIds,
      };

      // 根据操作类型添加额外参数
      switch (values.operation) {
        case 'update_status':
          operationData.status = values.status;
          break;
        case 'update_role':
          operationData.role = values.role;
          break;
        case 'reset_password':
          operationData.new_password = values.password;
          break;
        case 'send_notification':
          operationData.notification = {
            title: values.notification_title,
            content: values.notification_content,
          };
          break;
      }

      await batchOperateUsers(operationData);
      
      const operationNames = {
        delete: '删除',
        update_status: '状态修改',
        update_role: '角色修改',
        reset_password: '密码重置',
        send_notification: '通知发送',
      };
      
      message.success(`批量${operationNames[values.operation as keyof typeof operationNames]}成功`);
      onSuccess();
    } catch (error) {
      message.error('批量操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 用户列表表格列
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role: string) => {
        const roleMap = { admin: '管理员', user: '用户' };
        return roleMap[role as keyof typeof roleMap];
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = { active: '正常', inactive: '未激活', banned: '已封禁' };
        return statusMap[status as keyof typeof statusMap];
      },
    },
  ];

  // 渲染操作参数表单
  const renderOperationParams = () => {
    switch (operationType) {
      case 'update_status':
        return (
          <Form.Item
            name="status"
            label="新状态"
            rules={[{ required: true, message: '请选择新状态' }]}
          >
            <Radio.Group options={statusOptions} />
          </Form.Item>
        );
      
      case 'update_role':
        return (
          <Form.Item
            name="role"
            label="新角色"
            rules={[{ required: true, message: '请选择新角色' }]}
          >
            <Radio.Group options={roleOptions} />
          </Form.Item>
        );
      
      case 'reset_password':
        return (
          <Form.Item
            name="password"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, max: 20, message: '密码长度为6-20个字符' },
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
        );
      
      case 'send_notification':
        return (
          <>
            <Form.Item
              name="notification_title"
              label="通知标题"
              rules={[{ required: true, message: '请输入通知标题' }]}
            >
              <Input placeholder="请输入通知标题" />
            </Form.Item>
            <Form.Item
              name="notification_content"
              label="通知内容"
              rules={[{ required: true, message: '请输入通知内容' }]}
            >
              <Input.TextArea
                rows={4}
                placeholder="请输入通知内容"
                maxLength={500}
                showCount
              />
            </Form.Item>
          </>
        );
      
      case 'delete':
        return (
          <div style={{ 
            padding: '16px', 
            backgroundColor: '#fff2f0', 
            border: '1px solid #ffccc7',
            borderRadius: '6px',
            marginBottom: '16px'
          }}>
            <p style={{ color: '#cf1322', margin: 0 }}>
              ⚠️ 警告：删除操作不可恢复，请确认要删除选中的 {selectedUsers.length} 个用户。
            </p>
          </div>
        );
      
      default:
        return null;
    }
  };

  return (
    <Modal
      title={`批量操作 (已选择 ${selectedUsers.length} 个用户)`}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={800}
      destroyOnClose
      okButtonProps={{
        danger: operationType === 'delete',
      }}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          operation: '',
        }}
      >
        <Form.Item
          name="operation"
          label="操作类型"
          rules={[{ required: true, message: '请选择操作类型' }]}
        >
          <Select
            placeholder="请选择操作类型"
            onChange={handleOperationTypeChange}
            options={operationOptions}
          />
        </Form.Item>

        {renderOperationParams()}

        <div style={{ marginTop: '16px' }}>
          <h4>选中的用户列表：</h4>
          <Table
            columns={columns}
            dataSource={selectedUsers}
            rowKey="id"
            pagination={false}
            size="small"
            scroll={{ y: 200 }}
          />
        </div>
      </Form>
    </Modal>
  );
};

export default BatchOperationModal;
